package com.runa.monitor.platinterface.netservice.equipment;

import com.runa.monitor.platinterface.base.async.FutureDataTask;
import com.runa.monitor.platinterface.netservice.connect.*;
import com.runa.monitor.platinterface.netservice.connect.commstatus.CommStatus;
import com.runa.protocol.dto.IRequestData;
import com.runa.protocol.enums.ModbusType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zhuj
 */
public class NormalPlcService extends PlcService {

    private static final Logger logger = LoggerFactory.getLogger(NormalPlcService.class);

    private String ip;

    private int port;

    private int timeoutCount;

    public NormalPlcService(Integer id, int slaveId, Integer limit, boolean tcpAsync,
                            Integer timeout, ModbusType modbusType, String ip, int port, FutureDataTask task) {
        super(id, slaveId, limit, timeout, modbusType, task);
        this.ip = ip;
        this.port = port;
        Session session;
        if (tcpAsync) {
            session = new TellSession(getTimeout());
            ((TellSession) session).corrPlcService(this);
        } else {
            session = new AsyncCacheSession(this, getTimeout());
        }
        setSession(session);
    }

    @Override
    public IRequest<IRequestData> createReq(IRequestData requestData) {
        return new GeneralRequest(requestData, this);
    }

    @Override
    void timeoutOverLimit(CommStatus status) {
        if (CommStatus.TimeOut.equals(status)) {
            timeoutCount ++;
            logger.info("PLC {} 超时次数 {}", getId(), timeoutCount);
        } else {
            timeoutCount = 0;
        }
        if (timeoutCount >= 3) {
            logger.info("PLC {} 超时次数 {} 超过3次，开始重连", getId(), timeoutCount);
            this.session().close();
            timeoutCount = 0;
        }
    }

    public String getIp() {
        return ip;
    }

    public int getPort() {
        return port;
    }

    public void connected() {}
}
